//
//  AppDelegate.swift
//  仿新浪微博
//
//  Created by 罗超 on 2017/5/3.
//  Copyright © 2017年 LuoChao. All rights reserved.
//

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 取得用户授权显示通知[上方的提示条、声音、badgeNumber]
        // #available 检测设备版本在 10.0 以上
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .carPlay, .sound]) { (success, error) in
                print("授权" + (success ? "成功" : "失败"))
            }
        } else {
            // iOS 10 后已废弃
            let notifySetting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(notifySetting)
        }
        
//        sleep(1)
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        
        window?.rootViewController = WBMainViewController()
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }

}

// MARK: - 从服务器加载应用程序信息
extension AppDelegate {
    
    fileprivate func loadAppInfo() {
        DispatchQueue.global().async {
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            let data = NSData(contentsOf: url!)
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            // 下载后直接保存到沙盒, 等待下一次程序启动使用!
            data?.write(toFile: jsonPath, atomically: true)
            
            print("应用程序加载完毕 - \(jsonPath)")
        }
    }
    
}
